extends Node

# 游戏如何保存. 这个是两个局限性
# 1. 只有子场景才可以保存，节点是没有保存的
# 2. 需要删除重新创建一个新子场景

var save_game_path = "user://savegame.save"

# Note: This can be called from anywhere inside the tree. This function is
# path independent.
# Go through everything in the persist category and ask them to return a
# dict of relevant variables.
func save_game():
	var save_g = FileAccess.open_encrypted_with_pass(save_game_path, FileAccess.WRITE,  OS.get_unique_id())
	var save_nodes = get_tree().get_nodes_in_group("Persist")
	for node in save_nodes:
		# Check the node is an instanced scene so it can be instanced again during load.
		#if node.scene_file_path.is_empty():
			#print("persistent node '%s' is not an instanced scene, skipped" % node.name)
			#continue

		# Check the node has a save function.
		if !node.has_method("get_save_data"):
			print("persistent node '%s' is missing a save() function, skipped" % node.name)
			continue

		# Call the node's save function.
		var node_data = node.call("get_save_data")

		# JSON provides a static method to serialized JSON string.
		var json_string = JSON.stringify(node_data)

		# Store the save dictionary as a new line in the save file.
		save_g.store_line(json_string)

 #Note: This can be called from anywhere inside the tree. This function
# is path independent.
func load_game():
	if not FileAccess.file_exists(save_game_path):
		return # Error! We don't have a save to load.
		
	# We need to revert the game state so we're not cloning objects
	# during loading. This will vary wildly depending on the needs of a
	# project, so take care with this step.
	# For our example, we will accomplish this by deleting saveable objects.
	# 删除以重建
	#var save_nodes = get_tree().get_nodes_in_group("Persist")
	#for i in save_nodes:
		#i.queue_free()

	# Load the file line by line and process that dictionary to restore
	# the object it represents.
	var save_g = FileAccess.open_encrypted_with_pass(save_game_path, FileAccess.READ,  OS.get_unique_id())
	while save_g.get_position() < save_g.get_length():
		#1. json 解析
		var json_string = save_g.get_line()
		var json = JSON.new()
		var parse_result = json.parse(json_string)
		if not parse_result == OK:
			print("JSON Parse Error: ", json.get_error_message(), " in ", json_string, " at line ", json.get_error_line())
			continue
			
		#2. 加载数据
		var node_data = json.get_data()
		var new_object = get_node(node_data["path"])
		if !new_object.has_method("load_save_data"):
			print("persistent node '%s' is missing a save() function, skipped" % new_object.name)
			continue
		new_object.call("load_save_data",node_data)
		
		#3. 添加到场景中
		#get_node(node_data["parent"]).add_child(new_object)
			
func _on_save_bt_pressed():
	print("saving")
	save_game()


func _on_load_bt_pressed():
	print("loading")
	load_game()
